<template>
    <div class="login-container">
        <h1>用户登录</h1>
        <el-form :model="loginForm" @submit.native.prevent="handleLogin" class="login-form">
            <el-form-item label="用户名" :error="error">
                <el-input v-model="loginForm.username" id="username" placeholder="请输入用户名" required></el-input>
            </el-form-item>
            <el-form-item label="密码" :error="error">
                <el-input v-model="loginForm.password" id="password" type="password" placeholder="请输入密码" required></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" native-type="submit" class="login-button">登录</el-button>
            </el-form-item>
            <p v-if="error">{{ error }}</p>
        </el-form>
    </div>
</template>

<script>
import axios from '@/api/axios';

export default {
    data() {
        return {
            loginForm: {
                username: '',
                password: ''
            },
            error: null,
        };
    },
    methods: {
        async handleLogin() {
            try {
                const response = await axios.post('/loginUser', {
                    username: this.loginForm.username,
                    password: this.loginForm.password,
                });
                localStorage.setItem('token', response.data.data.token);
                await this.$router.push('/home');
            } catch (err) {
                this.error = '登录失败，请检查用户名和密码';
            }
        },
    },
};
</script>

<style scoped>
.login-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100vh; /* 全屏高度 */
    background: url('../../src/assets/images/wallhaven-kx65o7.png') no-repeat center center; /* 背景图片 */
    background-size: cover; /* 背景覆盖 */
    color: white; /* 字体颜色 */
}

.login-form {
    background: rgba(0, 0, 0, 0.7); /* 半透明背景 */
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.5);
    width: 350px; /* 设置表单宽度 */
}

h1 {
    margin-bottom: 20px;
    color: #e8e9ef; /* 设置标题颜色 */
}

.el-form-item {
    margin-bottom: 15px;
}

/* 设置按钮居中 */
.login-button {
    width: 100%; /* 按钮宽度100% */
}
</style>
